package cn.coastalinfo.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.NodeParser;
import cn.coastalinfo.common.utils.reflect.ReflectUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * 扩展 hutool TreeUtil 封装系统树构建
 *
 * @author Kaph Guan
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TreeBuildUtils extends TreeUtil {

    /**
     * 根据前端定制差异化字段
     */
    public static final TreeNodeConfig DEFAULT_CONFIG = TreeNodeConfig.DEFAULT_CONFIG.setNameKey("label");

    public static <T, K> List<Tree<K>> build(List<T> list, NodeParser<T, K> nodeParser) {
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        K k = ReflectUtils.invokeGetter(list.get(0), "parentId");
        return TreeUtil.build(list, k, DEFAULT_CONFIG, nodeParser);
    }

    public static <T, E> Tree<E> buildSingle(List<T> list, E rootId, TreeNodeConfig treeNodeConfig, NodeParser<T, E> nodeParser) {
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        E k = ReflectUtils.invokeGetter(list.get(0), "parentId");
        return TreeUtil.buildSingle(list, k, DEFAULT_CONFIG, nodeParser);
    }

    /**
     * 递归方法
     * @param tree 父节点对象
     * @param treeList 所有的List
     * @return
     */
//    public static T findChildren(T tree, List<T> treeList) {
//        for (T node : treeList) {
//            if (ReflectUtils.invokeGetter(tree, "id").equals(ReflectUtils.invokeGetter(tree, "parentId"))) {
//                if (ReflectUtils.invokeGetter(tree, "children") == null) {
//                    tree.setChildren(new ArrayList<>());
//                }
//                // 递归 调用自身
//                tree.getChildren().add(findChildren(node, treeList));
//            }
//        }
//        return tree;
//    }
}
